<template>
  <div class="container">
    <el-card>
      <p v-html="id ? '试题修改' : '试题录入'"></p>

      <el-form
        label-width="100px"
        :rules="questionRules"
        ref="questionRef"
        :model="questionForm"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            v-model="questionForm.subjectID"
            placeholder="请选择"
            @change="subjectChange"
          >
            <el-option
              v-for="(item, index) in subjectOption"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="questionForm.catalogID" placeholder="请选择">
            <el-option
              v-for="(item, index) in directoryOption"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="questionForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="(item, index) in company"
              :key="index"
              :label="item.shortName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
          <el-select
            v-model="questionForm.province"
            placeholder="请选择"
            @change="provinceChange"
          >
            <el-option
              v-for="(item, index) in provinceOption"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-select v-model="questionForm.city" placeholder="请选择">
            <el-option
              v-for="(item, index) in cityOption"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="questionForm.direction" placeholder="请选择">
            <el-option
              v-for="(item, index) in direction"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio
            v-model="questionForm.questionType"
            label="1"
            @change="questionTypeChange"
          >
            单选
          </el-radio>
          <el-radio
            v-model="questionForm.questionType"
            label="2"
            @change="questionTypeChange"
          >
            复选
          </el-radio>
          <el-radio
            v-model="questionForm.questionType"
            label="3"
            @change="questionTypeChange"
          >
            简答
          </el-radio>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio v-model="questionForm.difficulty" label="1">
            简单
          </el-radio>
          <el-radio v-model="questionForm.difficulty" label="2">
            一般
          </el-radio>
          <el-radio v-model="questionForm.difficulty" label="3">
            困难
          </el-radio>
        </el-form-item>
        <el-form-item label="题干：">
          <!-- 富文本编辑器组件 -->
          <quill-editor
            v-model="questionForm.question"
            :options="editorOption"
          />
        </el-form-item>
        <el-form-item
          label="选项："
          v-if="
            questionForm.questionType == 1 || questionForm.questionType == 2
          "
        >
          <!-- 选项 -->
          <el-radio-group
            v-model="radioValue"
            v-if="questionForm.questionType == 1"
            @change="changeRadio"
          >
            <div
              v-for="(item, index) in questionForm.options"
              :key="index"
              class="options"
            >
              <el-radio :label="item.code" class="optionsradio">
                {{ item.code }}:
                <el-input v-model="item.title" style="width: 500px"></el-input>
              </el-radio>
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
              >
                <div v-if="imgURL[index]" class="imgbox">
                  <img :src="imgURL[index]" />
                  <i
                    class="el-icon-circle-close"
                    @click.stop="clearImg(index)"
                  ></i>
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-radio-group>
          <!-- 多选 -->
          <el-checkbox-group
            v-model="optionValue"
            v-else
            @change="changeCheckbox"
          >
            <el-checkbox
              :label="item.code"
              v-for="item in questionForm.options"
              :key="item.id"
            >
              {{ item.code }}:<el-input
                v-model="item.title"
                style="margin-left: 10px"
              ></el-input>
            </el-checkbox>
          </el-checkbox-group>
          <!-- 添加答案按钮 -->
          <el-row>
            <el-col>
              <el-button
                type="danger"
                style="margin-top: 20px"
                :disabled="questionForm.questionType == 1"
                @click="addpro"
                >+增加选项与答案
              </el-button>
            </el-col>
          </el-row>
          <!-- /选项结束 -->
        </el-form-item>
        <el-form-item label="解析视频">
          <el-input
            v-model="questionForm.videoURL"
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item label="答案解析" prop="answer">
          <!-- 富文本编辑器组件 -->
          <quill-editor v-model="questionForm.answer" :options="editorOption" />
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="questionForm.remarks"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="试题标签">
          <el-select
            v-model="tags"
            multiple
            placeholder="请选择"
            @change="tagsChange"
          >
            <el-option
              v-for="(item, index) in tagsOption"
              :key="index"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" v-if="id" @click="edit(id)"
            >确认修改</el-button
          >
          <el-button type="primary" @click="add()" v-else>确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple as simpleSubjectList } from '@/api/hmmm/subjects'
import { simple as simpleDirectoryList } from '@/api/hmmm/directorys'
import { simple as tagsSimpleList } from '@/api/hmmm/tags'
import { list as listcommpanys } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { detail, update, add } from '@/api/hmmm/questions'

export default {
  created() {
    this.getSubjectList()
  },
  data() {
    return {
      questionForm: {
        /* 选择框绑定数据 */
        subjectID: '', //学科级联框绑定数据
        catalogID: '', //二级目录级联选择框
        tags: '', //标签级联选择框绑定数据
        questionType: '', //试题类型
        difficulty: '', //难度
        province: '', //企业所在省份
        city: '', //企业所在城市
        remarks: '', //目录备注
        direction: '', //方向
        enterpriseID: '', //企业
        question: '', //题干
        difficulty: '',
        videoURL: '', // 视频解析
        remarks: '', //题目备注
        answer: '', //答案解析
        options: [
          {
            code: '', // 代码
            title: '', // 标题
            img: '', //图片URL
            isRight: 0, //是否正确答案
          },
        ], // 选项
      },
      tags: [],
      /* 选择框选项数 */
      subjectOption: [], //学科级联选择框选项数据
      directoryOption: [], //二级目录级联选项数据
      tagsOption: [], //标签选择框选项数据
      company: [], //企业
      direction,
      provinceOption: provinces(),
      cityOption: [],
      // 修改富文本里面的toolbar
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block', 'image', 'link'],
          ],
        },
      },
      // 复选框选中
      option: [],
      id: this.$route.query.id, //动态传参过来的id值
      radioValue: null,
      optionValue: [],
      questionRules: {
        subjectID: [{ required: true, message: '请输入学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请输入目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请输入企业', trigger: 'blur' },
        ],
        province: [{ required: true, message: '请输入城市', trigger: 'blur' }],
        direction: [{ required: true, message: '请输入方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请输入学科题型', trigger: 'blur' },
        ],
        difficulty: [
          { required: true, message: '请输入学科难度', trigger: 'blur' },
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' },
        ],
      },
      imgURL: [],
    }
  },
  methods: {
    async getSubjectList() {
      console.log(this.questionForm)
      const { data: res } = await simpleSubjectList()
      this.subjectOption = res
      const { data } = await listcommpanys({
        page: 1,
        pagesize: 30,
      })
      this.company = data.items
      if (!this.questionForm.tags == '') {
        this.tags = this.questionForm.tags.split(',')
      } else {
        this.tags = []
      }
      if (this.id) {
        const id = this.id
        const { data } = await detail({ id })
        this.questionForm = data
        if (this.questionForm.questionType == 1) {
          const value = this.questionForm.options.find((item) => {
            return item.isRight == 1
          })
          this.radioValue = value.code
        } else {
          this.questionForm.options.forEach((item) => {
            if (item.isRight == 1) this.optionValue.push(item.code)
          })
        }
        const { data: directorys } = await simpleDirectoryList({
          subjectID: this.questionForm.subjectID.toString(),
        })
        this.directoryOption = directorys
      }
    },
    //学科列表选择框发生变化
    async subjectChange() {
      try {
        //请求二级目录级联选择框选项数据
        // 清空二级目录和标签
        this.questionForm.city = ''
        this.questionForm.catalogID = ''
        this.directoryOption = []
        this.tagsOption = []
        this.tags = []
        const { data: directorys } = await simpleDirectoryList({
          subjectID: this.questionForm.subjectID.toString(),
        })
        //请求标签级联选择框选项数据
        const { data: tags } = await tagsSimpleList({
          subjectID: this.questionForm.subjectID.toString(),
        })
        this.tagsOption = tags
        this.directoryOption = directorys
      } catch (error) {
        console.log(error)
        this.$message.error('获取二级目录失败')
      }
    },
    //省份选择框发生变化
    provinceChange() {
      this.cityOption = citys(this.questionForm.province)
      this.questionForm.city = ''
    },
    add() {
      console.log(this.questionForm)
    },
    questionTypeChange(val) {
      console.log(val)
      if (!this.id) {
        if (this.questionForm.questionType == 1) {
          this.questionForm.options = [
            {
              code: 'A',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'B',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'C',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'D',
              title: '',
              img: '',
              isRight: 0,
            },
          ]
        } else {
          this.questionForm.options = [
            {
              code: 'A',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'B',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'C',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'D',
              title: '',
              img: '',
              isRight: 0,
            },
            {
              code: 'E',
              title: '',
              img: '',
              isRight: 0,
            },
          ]
        }
      }
    },
    changeRadio(val) {
      this.questionForm.options.forEach((item) => {
        if (item.code === val) {
          item.isRight = 1
        } else item.isRight = 0
      })
      console.log(this.questionForm.options)
    },
    changeCheckbox(val) {
      console.log(val)

      this.questionForm.options.forEach((item) => {
        if (val.indexOf(item.title) !== -1) item.isRight = 1
        else item.isRight = 0
      })
      console.log(this.questionForm.options)
    },
    async edit(id) {
      try {
        let updateForm = {}
        Object.assign(updateForm, { id }, this.questionForm)
        console.log(updateForm)
        await update(updateForm)
        this.$message.success('修改题库成功')
        this.$router.push('list')
      } catch (err) {
        this.$message.error('操作失败')
      }
    },
    // 添加按钮
    add() {
      this.$refs.questionRef.validate(async (valid) => {
        if (valid) {
          try {
            await add(this.questionForm)
            this.$message.success('添加题库成功')
            this.$router.push('list')
          } catch (error) {
            console.log(error)
            this.$message.error('操作失败')
          }
        } else {
          return false
        }
      })
    },
    // 增加选项
    addpro() {
      let title = this.questionForm.options[
        this.questionForm.options.length - 1
      ].code
      let optionstitle = title.charCodeAt()
      optionstitle++
      optionstitle = String.fromCharCode(optionstitle)
      this.questionForm.options.push({
        code: optionstitle,
        title: '',
        img: '',
        isRight: 0,
      })
    },
    //上传图片
    handleUploadSuccess(res, file, filelist) {
      console.log(res, file, filelist)
      // this.imgURL = URL.createObjectURL(file.raw)
      filelist.forEach((item) => {
        this.imgURL.push(URL.createObjectURL(item.raw))
      })
      console.log(this.imgURL)
    },
    clearImg(index) {
      this.imgURL.splice(index, 1)
    },

    tagsChange() {
      this.questionForm.tags = this.tags.join(',')
      console.log(this.questionForm.tags)
    },
  },
}
</script>

<style scoped lang='less'>
.quill-editor {
  height: 150px;
  margin-bottom: 50px;
  /deep/img {
    height: 100px;
  }
}

.Uploadfile {
  position: relative;
  margin-left: 10px;
  text-align: center;
  width: 100px;
  height: 60px;
  line-height: 60px;
  display: inline-block;
  border: 1px dashed #ccc;
  color: #333;
  cursor: pointer;
}

.el-icon-error {
  position: absolute;
  left: 90px;
  top: -6px;
}
.optionsradio,
.el-checkbox {
  display: block;
  margin-bottom: 20px;
}
/deep/.avatar-uploader .el-upload {
  display: inline-block;
  border: 1px dashed #333;
  border-radius: 6px;
  cursor: pointer;
  // position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.options {
  display: flex;
  align-items: center;
  height: 100px;
  font-size: 14px;
  .imgbox {
    position: relative;
    img {
      width: 100px;
      height: 80px;
    }
    i {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 80px;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
}
</style>